/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun<iot25@lingyun>
 *                  All rights reserved.
 *
 *       Filename:  get_temp.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(07/04/25)
 *         Author:  LingYun <iot25@lingyun>
 *      ChangeLog:  1, Release initial version on "07/04/25 20:54:57"
 *                 
 ********************************************************************************/
#include<stdio.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<dirent.h>
#include<stdlib.h>
#include<time.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>

#include"logger.h"


int get_temp(float *temp)
{
	if(  !temp ) //检查传入的指针 temp 是否为 NULL。如果是，记录错误日志并返回 -1。
	{
		log_error("Invalid input argument");
		return -1;
    }

	char			 dev_path[128] = "/sys/bus/w1/devices/";
	DIR			    *dev_pathfd = NULL;
	struct dirent	*dev_dir = NULL;
	char		 	 chip_name[128] = {0};
	int		 	     fd = -1;
	char		 	 buf[128] = {0};
	char			*data = NULL;
	int 		 	 found_flag = 0;
	int		          n = 0;

	/*打开设备路径*/
	if( NULL == (dev_pathfd = opendir(dev_path)) )
	{
		log_error("open dev_path failure: %s", strerror(errno));
		return -1;
	}
	log_debug("Open dev_path: \"%s\" successfully.\n", dev_path);

	/*读取设备的信息*/
	if( NULL == (dev_dir = readdir(dev_pathfd)) )
	{
		log_error("Read dev_dir failure: %s", strerror(errno));
		return -2;
	}

	while( NULL != (dev_dir = readdir(dev_pathfd)) )
	{

		if( strstr(dev_dir->d_name, "28-") )
		{
			strncpy(chip_name, dev_dir->d_name, sizeof(chip_name));
			found_flag = 1;
		}
	}

	if( !found_flag )
	{
		log_error("read dev_dir failure: %s", strerror(errno));
		return -3;
	}

	/*生成设备的完整路径*/
	strncat(dev_path, chip_name, (sizeof(dev_path) - strlen(dev_path)));
	strncat(dev_path, "/w1_slave", (sizeof(dev_path) - strlen(dev_path)));
	log_debug("The full path is: \"%s\"\n", dev_path);

	closedir(dev_pathfd);

	/*打开设备的完整路径和文件*/
	if( (fd = open(dev_path, O_RDONLY)) < 0 )
	{
		log_error("open full path and file failure: %s", strerror(errno));
		return -4;
	}

	/*读取设备文件*/
	if( (n = read(fd, buf, sizeof(buf))) < 0 )
	{
		log_error("read the file failure: %s", strerror(errno));
		return -5;
	}

	/*获取温度*/
	if( NULL == (data = strstr(buf, "t=")) )
	{
		log_error("get temperature failure: %s", strerror(errno));
		return -6;
	}
	data += 2;
	*temp = atof(data)/1000;
	log_debug("get_temp successfully: %f", *temp);


	close(fd);
	return 0;
}



